<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="uid" placeholder="请输入你的id"/>
    <br>
    <button onclick="onConnectionClick();">点击连接服务器</button>
    <span id="connectionInfo"></span>
    <br>
    <div id="msgs"></div>

    <script>
        let socket;
        function onConnectionClick(){
            if(typeof(WebSocket) == "undefined"){
                //浏览器不支持webSocket
                document.getElementById("connectionInfo").innerHTML="浏览器不支持webSocket";
            }else{
                //支持
                if(socket!=null){
                    //把上一次的连接关闭置空。
                    socket.close();
                    socket=null;
                }
                //获取用户输入的id
                let uid=document.getElementById("uid").value;
                //连接webSocket的url
                let url="ws://localhost:9004/webSocket/"+uid;
                //实例化WebSocket
                socket=new WebSocket(url);
                //四个回调
                socket.onopen=function(){
                    document.getElementById("connectionInfo").innerHTML="已经连接";
                    socket.send("你好，我是一个前端，刚刚连接上你的服务器。");
                };
                socket.onmessage=function(msg){
                    let receiveMessage=msg.data;
                    document.getElementById("msgs").innerHTML+="<span>"+receiveMessage+"</span><br>";
                };
                socket.onclose=function(){
                    document.getElementById("connectionInfo").innerHTML="已经断开";
                };
                socket.onerror=function(){
                    document.getElementById("connectionInfo").innerHTML="发生错误";
                };
            }
        }

    </script>
</body>
</html>